<?php

/**
 * 管理员的操作
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-07
 */

namespace app\admin\model;

use app\common\logic\Response;
use fw\base\Conf;
use fw\base\Instance;
use fw\db\DB;
use fw\tool\Request;
use fw\tool\String;

class Manager
{
    use Instance;

    /**
     * 新增一条数据
     *
     * @return array
     */
    public function add()
    {
        // 参数获取
        $name = Request::post('name', 'trim');
        $email = Request::post('email', 'trim');
        $password = Request::post('password', 'trim');
        $re_password = Request::post('re_password', 'trim');
        $parent_id = (int)Request::post('parent_id');
        $status = (int)Request::post('status', null, 1);

        // 参数校验
        if (empty($name) || strlen($name) > 50) {
            return Response::to([400, 'Parameter error, name too long or empty.']);
        }
        $pattern = '/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/';
        if (empty($email) || strlen($email) > 100 || preg_match($pattern, $email) < 1) {
            return Response::to([400, 'Parameter error, email illegal.']);
        }
        if (empty($password) || strlen($password) > 100) {
            return Response::to([400, 'Parameter error, password too long or empty.']);
        }
        if ($password != $re_password) {
            return Response::to([400, 'Parameter error, two passwords are not consistent.']);
        }

        $ret = $this->checkEmail($email);
        if ($ret != true) {
            return Response::to([400, 'Email disabled.', ['email' => $email]]);
        }

        // 数据准备
        $password = String::encrypt($password, $password);
        $signs = String::encrypt($email, $email);
        $data = [
            'name'        => $name,
            'email'       => $email,
            'password'    => $password,
            'create_time' => time(),
            'update_time' => 0,
            'parent_id'   => $parent_id,
            'status'      => $status,
            'signs'       => $signs,
        ];

        // 操作数据库
        $ret = DB::table('manager')->insert($data);

        if ($ret == false) {
            return Response::log([500, 'Insert fail.', $data], Request::post());
        }
        $manager_id = (int)$ret;

        return Response::to([0, 'Success.', ['manager_id' => $manager_id]]);
    }

    /**
     * 更新一条数据。
     *
     * @return array
     */
    public function update()
    {
        // 参数获取
        $manager_id = (int)Request::post('manager_id');
        $name = Request::post('name', 'trim');
        $email = Request::post('email', 'trim');
        $password = Request::post('password', 'trim');
        $re_password = Request::post('re_password', 'trim');
        $parent_id = (int)Request::post('parent_id');
        $status = (int)Request::post('status', null, 1);

        // 参数校验
        if (empty($name) || strlen($name) > 50) {
            return Response::to([400, 'Parameter error, name too long or empty.']);
        }
        $pattern = '/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/';
        if (empty($email) || strlen($email) > 100 || preg_match($pattern, $email) < 1) {
            return Response::to([400, 'Parameter error, email illegal.']);
        }
        if ($password != $re_password) {
            return Response::to([400, 'Parameter error, two passwords are not consistent.']);
        }

        // 查一遍旧数据，备用
        $info = DB::table('manager')->where('manager_id=:manager_id', [':manager_id' => $manager_id])->selectRow();
        if (empty($info)) {
            return Response::log([404, 'Record have not found.'], Request::post());
        }

        // 数据准备
        $data = [];
        if (!empty($name)) {
            $data['name'] = $name;
        }
        if (!empty($email) && $email !== trim($info['email'])) {
            $ret = $this->checkEmail($email);
            if ($ret != true) {
                return Response::to([400, 'Email disabled.', ['email' => $email]]);
            }
            $data['email'] = $email;
            $data['signs'] = String::encrypt($email, $email);
        }
        if (!empty($password)) {
            $data['password'] = String::encrypt($password, $password);
        }
        if ($parent_id > -1) {
            $data['parent_id'] = $parent_id;
        }
        if ($status > -1) {
            $data['status'] = $status;
        }

        if (empty($data)) {
            return Response::to([400, 'Parameter error, data empty.']);
        }

        // 操作数据库
        $affected_rows = DB::table('manager')->where('manager_id=:manager_id', [':manager_id' => $manager_id])->update($data);
        if ($affected_rows == false) {
            return Response::to([200, 'Without any modification.', $data]);
        }

        $data = ['update_time' => time()];
        DB::table('manager')->where('manager_id=:manager_id', [':manager_id' => $manager_id])->update($data);

        return Response::to([0, 'Success.']);
    }

    /**
     * 校验 email 是否可用。
     *
     * @param $email 要校验的邮箱
     *
     * @return bool|array
     *  -- code = 102, 邮箱地址过长
     *  -- false, 校验不通过
     *  -- true,  校验通过
     */
    public function checkEmail($email)
    {
        // 参数获取
        $email = trim($email);

        // 参数校验
        if (empty($email) || strlen($email) > 100) {
            return [
                'code' => 400,
                'msg'  => 'Parameter error, email too long or empty.',
                'data' => [],
            ];
        }

        $info = DB::table('manager')->field('manager_id')->where('email=:email', [':email' => $email])->selectRow();

        return !empty($info) ? false : true;
    }

    /**
     * 查询一条指定数据
     *
     * @param  array $args
     *
     * @return array
     */
    public function getInfo($args)
    {
        // 参数获取
        $manager_id = (int)Request::input($args, 'manager_id');

        // 参数校验
        if ($manager_id < 1) {
            return [];
        }

        // 查询数据库
        $info = DB::table('manager')->where('manager_id=:manager_id', [':manager_id' => $manager_id])->selectRow();

        return $info;
    }

    /**
     * 查询符合条件的数据列表
     *
     * @param $args
     *
     * @return array|int
     */
    public function getList($args = null)
    {
        // 参数获取
        $fields = Request::input($args, 'fields', 'trim');
        $manager_ids = Request::input($args, 'manager_ids', 'trim');

        $page = Request::input($args, 'page', 'intval', 1);
        $length = Request::input($args, 'length', 'intval', 100);

        $sort_way = Request::input($args, 'sort_way', 'trim', 'DESC');
        $sort_way = strtoupper($sort_way);

        $is_count = Request::input($args, 'is_count', 'boolval', false);

        // 条件组装
        $prep = $map = [];
        if (!empty($manager_ids)) {
            $map[] = "manager_id IN(:mid1)";
            $prep[':mid1'] = $manager_ids;
        }
        $map[] = 'manager_id<>:mid2';
        $prep[':mid2'] = Conf::$all['super_user'];
        $where = implode(' AND ', $map);

        // 查询条数
        if ($is_count === true) {
            return DB::table('manager')->where($where, $prep)->count();
        }

        // 查询列表
        $ret = DB::table('manager')
            ->where($where, $prep)
            ->order('manager_id ' . $sort_way)
            ->limit(($page - 1) * $length . ',' . $length)
            ->field($fields)
            ->select();

        return $ret;
    }

    /**
     * 删除数据
     *
     * @param array $args
     *
     * @return array
     */
    public function del($args)
    {
        // 参数获取
        $manager_id = (int)Request::input($args, 'manager_id');
        $op_user = (int)Request::input($args, 'op_user');

        // 参数校验
        if ($manager_id < 1 || $op_user < 1) {
            return Response::to([400, 'Parameter error.']);
        }

        // 查询信息
        $info = DB::table('manager')->where('manager_id=:manager_id', [':manager_id' => $manager_id])->selectRow();
        if (empty($info)) {
            return Response::to([404, 'Record does not exists.']);
        }

        // 放入回收站
        Recy::gi()->add('manager', $info, $op_user);

        // 删除
        $affected_rows = DB::table('manager')->where('manager_id=:manager_id', [':manager_id' => $manager_id])->delete();
        if ($affected_rows == false) {
            return Response::log([500, 'Delete fail.'], $args);
        }

        return Response::to([0, 'Success.']);
    }
}
